package com.frame.project.controller.system.user;

import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.frame.common.constant.UserConstants;
import com.frame.common.utils.page.MyPage;
import com.frame.common.utils.poi.ExcelUtil;
import com.frame.common.utils.security.ShiroUtils;
import com.frame.framework.aspectj.lang.annotation.Log;
import com.frame.framework.aspectj.lang.enums.BusinessType;
import com.frame.framework.web.controller.BaseController;
import com.frame.framework.web.error.WebError;
import com.frame.framework.web.error.enums.WebEnum;
import com.frame.framework.web.page.TableDataInfo;
import com.frame.project.domain.system.user.User;
import com.frame.project.domain.system.user.UserRole;
import com.frame.project.service.system.post.PostService;
import com.frame.project.service.system.role.RoleService;
import com.frame.project.service.system.user.UserService;

/**
 * 用户信息
 * 
 */
@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController
{
    private String prefix = "system/user";

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PostService postService;

    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user()
    {
        return prefix + "/user";
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(User user,@RequestParam(defaultValue = "0") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize)
    {
        startPage();
        MyPage<User> findByPage = userService.findByPage(user, pageNum, pageSize);
        return getDataTable(findByPage);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @ResponseBody
    public WebError export(User user)
    {
    	MyPage<User> page = userService.findByPage(user, 0, Integer.MAX_VALUE);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.exportExcel(page.getContent(), "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public WebError importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        List<User> userList = util.importExcel(file.getInputStream());
        String message = userService.importUser(userList, updateSupport);
        return success(0,message);
    }

    @RequiresPermissions("system:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public WebError importTemplate()
    {
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("roles", roleService.selectRoleAll());
        mmap.put("posts", postService.selectPostAll());
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public WebError addSave(@Validated User user)
    {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName())))
        {
            return error(-1,"新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error(-1,"新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error(-1,"新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        userService.insertUser(user);
        return success();
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, Model model)
    {
    	User u = userService.findById(userId);
    	model.addAttribute("user", userService.findById(userId));
    	model.addAttribute("roles", roleService.selectRolesByUserId(userId));
    	model.addAttribute("posts", postService.selectPostsByUserId(userId));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public WebError editSave(@Validated User user)
    {
        WebError web = userService.checkUserAllowed(user.getId());
        if(web.getCode() == -1) {
        	return web;
        }
        
        if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error(-1,"修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error(-1,"修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        userService.updateUser(user);
        return success();
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, Model model)
    {
    	model.addAttribute("user", userService.findById(userId));
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public WebError resetPwdSave(User user)
    {
    	WebError web = userService.checkUserAllowed(user.getId());
        if(web.getCode() == -1) {
        	return web;
        }
        
        if (userService.resetUserPwd(user))
        {
            if (ShiroUtils.getUserId().longValue() == user.getId())
            {
                setSysUser(userService.findById(user.getId()));
            }
            return success();
        }
        return error(WebEnum.ERROR);
    }

    /**
     * 进入授权角色页
     */
    @GetMapping("/authRole/{userId}")
    public String authRole(@PathVariable("userId") Long userId, Model model)
    {
        User user = userService.findById(userId);
        // 获取用户所属的角色列表
        List<UserRole> userRoles = userService.selectUserRoleByUserId(userId);
        model.addAttribute("user", user);
        model.addAttribute("userRoles", userRoles);
        return prefix + "/authRole";
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PostMapping("/authRole/insertAuthRole")
    @ResponseBody
    public WebError insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public WebError remove(String ids)
    {
    	return userService.deleteUserByIds(ids);
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(User user)
    {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(User user)
    {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(User user)
    {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public WebError changeStatus(User user)
    {
    	WebError web = userService.checkUserAllowed(user.getId());
        if(web.getCode() == -1) {
        	return web;
        }
        userService.changeStatus(user);
        return success();
    }
}